<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
<div class="container">
<!--表单注册-->
<form id="myform">
    <!--username=1231&password=1231 默认表单的提交方式-->
    <div class="form-group">
        <label for="username" class="control-label">用户名</label>
        <input type="text" class="form-control" name="username" id="username">
    </div>
    <div class="form-group">
        <label for="password" class="control-label">密码</label>
        <input type="text" class="form-control" name="password" id="password">
    </div>
    <div class="form-group">
        <button id="btn" type="button" class="btn btn-primary btn-lg">注册</button>
    </div>
</form>
    <ul id="oUl" class="list-group">

    </ul>
</div>
<script>
    function serialize(form) {
        //获取表单内所有元素
        //获取表单内所有元素；
        //将类数组转换成数组
        var formAry=[].slice.call(form.elements);
        var arr=[];
        formAry.forEach(function (item) {
            if(item.type!='text') return;
            arr.push(`${item.name}=${item.value}`);
        });
        return arr.join('&');
    }
    btn.onclick = function () {
        var xhr = new XMLHttpRequest();
        xhr.open('POST','/user',true);
        //指定响应类型
        xhr.responseType='json';
        xhr.onload = function () {
            var data = xhr.response; //用户集合
            console.log(data);
            var str = '';
            data.forEach(function (item,index) {
                str+=`<li style="overflow: hidden" class="list-group-item">
                        ${item.username}:${item.password}
                        <button style="float: right" class="btn btn-danger" onclick="remove.call(this,${item.id})">删除</button>
                    </li>`;
            });
            oUl.innerHTML = str;
        };
        xhr.send(serialize(myform));
    }
    function remove(index) {
        var that = this;
        var xhr = new XMLHttpRequest();
        xhr.open('DELETE','/user?id='+index,true);
        xhr.responseType='json';
        xhr.onload = function () {
            if(xhr.response.success=='done'){
                alert('删除成功');
                //后台删除成功后前台也要删掉
                that.parentNode.parentNode.removeChild(that.parentNode);
            }
        };
        xhr.send();
    }


</script>

</body>
</html>